package com.senlingspace.framework.security.filter;

import com.senlingspace.common.utils.JwtUtilExt;
import com.senlingspace.framework.config.properties.ProtectUriProperties;
import com.senlingspace.framework.security.context.SecurityContextHolderExt;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * 全局过滤器
 *
 * @author lebronjames
 */
@Slf4j
@AllArgsConstructor
@Component
public class GlobalFilter implements Filter {

    private final ProtectUriProperties protectUriProperties;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();

        String shopId = request.getHeader("Wx-Shop-Id");
        if (StringUtils.isNotBlank(shopId)) {
            SecurityContextHolderExt.setShopId(Long.parseLong(shopId));
        }

        // 只处理微信小程序接口
        if (uri.startsWith("/wmp/")) {
            String authorization = request.getHeader("Wx-Authorization");
            log.info("当前请求为微信小程序接口：URI = {}, Wx-Authorization = {}, Wx-Shop-Id = {}", uri, authorization, shopId);

            String pageNumStr = request.getParameter("pageNum");
            String pageSizeStr = request.getParameter("pageSize");

            int pageNum = StringUtils.isNotBlank(pageNumStr) ? Integer.parseInt(pageNumStr) : 1;
            int pageSize = StringUtils.isNotBlank(pageSizeStr) ? Integer.parseInt(pageSizeStr) : 10;

            SecurityContextHolderExt.set("page_num", pageNum);
            SecurityContextHolderExt.set("page_size", pageSize);

            // 微信小程序授权验证
            boolean uriMatched = protectUriProperties.getUris()
                    .stream()
                    .anyMatch(protectedUri -> {
                        // 如果是以 /** 结尾的 URI，转换为正则表达式进行匹配
                        if (protectedUri.endsWith("/**")) {
                            String regex = protectedUri.substring(0, protectedUri.length() - 3) + ".*";
                            return Pattern.matches(regex, uri);
                        }
                        // 如果是以 /* 结尾的 URI，匹配单层路径
                        if (protectedUri.endsWith("/*")) {
                            String regex = protectedUri.substring(0, protectedUri.length() - 2) + "/[^/]+";
                            return Pattern.matches(regex, uri);
                        }
                        // 否则进行直接匹配
                        return uri.equals(protectedUri);
                    });

            if (uriMatched) {
                log.info("当前请求 {} 在名单内，需验证token信息！", uri);
                if (StringUtils.isNotBlank(authorization)) {
                    SecurityContextHolderExt.setToken(authorization);
                    JwtUtilExt.Payload payload = JwtUtilExt.parseToken(authorization);
                    if (Objects.nonNull(payload)) {
                        SecurityContextHolderExt.setCustomerId(payload.getCustomerId());
                        SecurityContextHolderExt.setCustomerMobile(payload.getPhone());
                    }
                }
            }
        }

        filterChain.doFilter(request, response);
    }

}
